package com.navinfo.tripanalysis.common.util;


import com.navinfo.tripanalysis.common.config.ConfigMap;
import java.util.concurrent.*;

/**
 * @author 水哥
 */
public class ThreadPoolUtils {

    private static ThreadPoolExecutor executor;

    private static ThreadPoolExecutor getInstance() {
        if (executor == null) {
            synchronized (ThreadPoolUtils.class) {
                if (executor == null) {
                    ThreadFactory threadFactory = Executors.defaultThreadFactory();
                    RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
                    LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>();
                    executor = new ThreadPoolExecutor(
                            //corePoolSize最好设置大于jstorm的worker数量
                            ConfigMap.getInteger("threadPool.corePoolSize"),
                            ConfigMap.getInteger("threadPool.maximumPoolSize"),
                            200,
                            TimeUnit.MILLISECONDS,
                            workQueue,
                            threadFactory,
                            handler);
                }
            }
        }
        return executor;
    }

    /**
     * 执行任务.
     */
    public static void executeTask(Runnable runnable) {
        getInstance().execute(runnable);
    }

    /**
     * 执行任务
     */
    public static void submitTask(Runnable runnable) {
        getInstance().submit(runnable);
    }

    /**
     * 删除任务
     */
    public static void removeTask(Runnable r) {
        getInstance().remove(r);
    }

    /**
     * getPoolSize
     *
     * @return PoolSize
     */
    public static int getPoolSize() {
        return getInstance().getPoolSize();
    }

    /**
     * getQueueSize
     *
     * @return QueueSize
     */
    public static int getQueueSize() {
        return getInstance().getQueue().size();
    }

    /**
     * getCompletedTaskCount
     *
     * @return CompletedTaskCount
     */
    public static long getCompletedTaskCount() {
        return getInstance().getCompletedTaskCount();
    }
}
